package com.ruoyi.report.controller;

import java.lang.reflect.Type;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.report.domain.DepotJsonDto;
import com.ruoyi.station.domain.RateDTO;
import com.ruoyi.system.mapper.SysUserMapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.report.domain.ReportOilDepot;
import com.ruoyi.report.service.IReportOilDepotService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;

/**
 * 油库Controller
 * 
 * @author ruoyi
 * @date 2024-10-15
 */
@RestController
@RequestMapping("/depot/depot")
public class ReportOilDepotController extends BaseController
{
    @Autowired
    private IReportOilDepotService reportOilDepotService;

    /**
     * 查询油库列表
     */
    @PreAuthorize("@ss.hasPermi('depot:depot:list')")
    @GetMapping("/list")
    public TableDataInfo list(ReportOilDepot reportOilDepot)
    {
        startPage();
        List<ReportOilDepot> list = reportOilDepotService.selectReportOilDepotList(reportOilDepot);
        return getDataTable(list);
    }
    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private Gson gson;
    /**
     * 导出油库列表
     */
    @PreAuthorize("@ss.hasPermi('depot:depot:export')")
    @Log(title = "油库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response ,ReportOilDepot reportOilDepot)
    {
        List<SysUser> sysUsers = userMapper.selectUserList(new SysUser());
        List<ReportOilDepot> list = reportOilDepotService.selectReportOilDepotList(reportOilDepot);
        for (ReportOilDepot oilDepot : list) {
            String extra2 = oilDepot.getExtra2();
            Type userType = new TypeToken<List<Long>>() {}.getType();
            List<Long> uids = gson.fromJson(extra2, userType);

            List<SysUser> correspondingReports = sysUsers.stream()
                    .filter(user -> uids.contains(user.getUserId())) // Assumes `ReportUserId` is now a collection of user IDs
                    .collect(Collectors.toList());

            String workNames = correspondingReports.stream()
                    .map(SysUser::getUserName)
                    .collect(Collectors.joining(", "));

            oilDepot.setWorkName(workNames);


            SysUser correspondingReport = sysUsers.stream()
                    .filter(user -> user.getUserId().equals(oilDepot.getReportUserId()))
                    .findFirst()
                    .orElse(null);
            oilDepot.setReportName(ObjectUtil.isNotEmpty(correspondingReport)?correspondingReport.getUserName():"");

        }
        ExcelUtil<ReportOilDepot> util = new ExcelUtil<ReportOilDepot>(ReportOilDepot.class);
         util.exportExcel(response,list, "油库数据");
    }

    /**
     * 获取油库详细信息
     */
    @PreAuthorize("@ss.hasPermi('depot:depot:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(reportOilDepotService.selectReportOilDepotById(id));
    }
@Autowired
private TokenService tokenService;
    /**
     * 新增油库
     */
    @PreAuthorize("@ss.hasPermi('depot:depot:add')")
    @Log(title = "油库", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ReportOilDepot reportOilDepot)
    {

        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        reportOilDepot.setDeptId(loginUser.getUser().getDept().getDeptId());
        reportOilDepot.setCreateTime(DateUtils.getNowDate());


        Integer i = reportOilDepotService.countTodayRecordsDepot(reportOilDepot.getDeptId());
        if (i>=1){
            throw new RuntimeException("今日已有数据上报记录,请前往修改");
        }

        Gson gson = new Gson();
        List<DepotJsonDto> extra1 = reportOilDepot.getExtra1();
        List<DepotJsonDto> sendJson = reportOilDepot.getSendJson();
        if (CollectionUtil.isNotEmpty(extra1)){
            reportOilDepot.setExtra3(gson.toJson(extra1));
            reportOilDepot.setExtra4(gson.toJson(sendJson));
        }


        List<Long> workUsers = reportOilDepot.getWorkUsers();
        if (CollectionUtil.isNotEmpty(workUsers)){
            reportOilDepot.setExtra2(gson.toJson(workUsers));
        }
        reportOilDepot.setExtra1(null);
        reportOilDepot.setSendJson(null);


        return toAjax(reportOilDepotService.insertReportOilDepot(reportOilDepot));
    }

    /**
     * 修改油库
     */
    @PreAuthorize("@ss.hasPermi('depot:depot:edit')")
    @Log(title = "油库", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ReportOilDepot reportOilDepot)
    {
        Gson gson = new Gson();
        List<DepotJsonDto> extra1 = reportOilDepot.getExtra1();
        List<DepotJsonDto> sendJson = reportOilDepot.getSendJson();
        if (CollectionUtil.isNotEmpty(extra1)){
            reportOilDepot.setExtra3(gson.toJson(extra1));
            reportOilDepot.setExtra4(gson.toJson(sendJson));
        }
        reportOilDepot.setExtra1(null);
        reportOilDepot.setSendJson(null);

        List<Long> workUsers = reportOilDepot.getWorkUsers();
        if (CollectionUtil.isNotEmpty(workUsers)){
            reportOilDepot.setExtra2(gson.toJson(workUsers));
        }

        return toAjax(reportOilDepotService.updateReportOilDepot(reportOilDepot));
    }

    /**
     * 删除油库
     */
    @PreAuthorize("@ss.hasPermi('depot:depot:remove')")
    @Log(title = "油库", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(reportOilDepotService.deleteReportOilDepotByIds(ids));
    }
}
